<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <!-- <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      <!-- <el-form-item label="权限字符" prop="roleKey">
          <el-input
            v-model="queryParams.roleKey"
            placeholder="请输入权限字符"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      <!-- <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="角色状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="排班时间">
        <el-date-picker
          value-format="yyyy-MM"
          v-model="queryParams.workDate"
          type="month"
          placeholder="选择月"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" :disabled="!roleList.length>2" @click="addNewRecords"
          >添加三条记录</el-button
        >
      </el-col>
      <el-col :span="1.5"> </el-col>
      <el-col v-if="user == 'admin'" :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="roleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="日期" prop="workDate" />
      <el-table-column
        label="08:00-16:00"
        prop="workOne"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="16:00-24:00"
        prop="workTwo"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="上班员工" prop="taskLoad">
        <template slot-scope="scope">
          <span v-if="scope.row.followStatus == '已成单'">已成单 </span>
          <span v-else>{{ scope.row.workOne }},{{ scope.row.workTwo }}</span>
        </template>
      </el-table-column>

      <el-table-column label="休息员工" prop="restWorker" />

      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.complaintId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog
      @close="guanbishoukan"
      :title="title"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :visible.sync="xunkong"
    >
      <el-form
        :model="kesuwanfrom"
        :rules="kesuwanfromre"
        ref="xundanfrom"
        label-width="180px"
        class="demo-ruleForm"
      >
        <el-form-item prop="workDate" label="日期">
          <el-date-picker
            v-model="kesuwanfrom.workDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="workOne" label="08:00-16:00">
          <el-select v-model="kesuwanfrom.workOne" placeholder="请选择">
            <el-option
              v-for="item in chengdan"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="workTwo" label="16:00-24:00">
          <el-select v-model="kesuwanfrom.workTwo" placeholder="请选择">
            <el-option
              v-for="item in chengdan"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="xunkong = false">取 消</el-button>
        <el-button type="primary" @click="xundan">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole,
  dataScope,
  changeRoleStatus,
  deptTreeSelect,
} from "@/api/system/role";

import {
  deleteixundan,
  geipaiban,
  paizneg,
  deletepaiban,
  bianjixundan,
} from "@/api/new";

import { listUser ,listUssder} from "@/api/system/user";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "@/api/system/menu";

export default {
  name: "Role",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      ketui: "",
      jiaojie: "",
      dai: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      xunkong: false,
      // 非单个禁用
      single: true,
      now: "",
      hounow: 0,
      // 非多个禁用
      kesuwanfrom: {
        recordId: "",
        workDate: "",
        workOne: "",
        workTwo: "",
        restWorker: "",
        remake: null,
      },
      kesuwanfromre: {
        workDate: [
          { required: true, message: "日期不能为空", trigger: "blur" },
        ],
        workOne: [{ required: true, message: "员工不能为空", trigger: "blur" }],
        workTwo: [{ required: true, message: "员工不能为空", trigger: "blur" }],
        restWorker: [
          { required: true, message: "员工不能为空", trigger: "blur" },
        ],
      },
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      user: this.$store.state.user.name,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 数据范围选项

      yiwei: [
        {
          value: "已成单",
          label: "已成单",
        },
        {
          value: "未成单",
          label: "未成单",
        },
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        workDate: "",
      },
      chengdan: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" },
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" },
        ],
      },
      newRecords: [],
      currentIndex: 0, // 当前索引，用于循环
    };
  },
  created() {
    let date = new Date(new Date());
    this.queryParams.workDate =
      date.getFullYear() +
      "-" +
      (date.getMonth() + 1 < 10 ? "0" : "") +
      (date.getMonth() + 1);
    this.getList();
    this.getsList();
  },

  methods: {
    addNewRecords() {
      this.newRecords = [];
      let lastPersonIndex = this.chengdan.indexOf(this.chengdan[0]) + 1;
      let today = new Date(); // 获取当前日期
      if (this.roleList.length) {
        today = new Date(this.roleList[this.roleList.length - 1].workDate);
        today.setDate(today.getDate() + 1);
      }

      // if (this.roleList.length) {
      //   lastPersonIndex =
      //     this.roleList.indexOf(
      //       this.roleList[this.roleList.length - 1].workTwo
      //     ) + 1;
      // }
      // 循环五次，每次增加一天

      for (let day = 0; day < 3; day++) {
        const newDate = new Date(today);
        newDate.setDate(today.getDate() + day); // 设置新的日期

        // 格式化日期为 yyyy-mm-dd
        const formattedDate = `${newDate.getFullYear()}-${(
          newDate.getMonth() + 1
        )
          .toString()
          .padStart(2, "0")}-${newDate.getDate().toString().padStart(2, "0")}`;
  this.newRecords.push({
          recordId: "", // 可以根据需要设置
          workDate: formattedDate,
          workOne: '',
          workTwo: '',
          restWorker: '',
          remake: null,
        });

  

      }

      if(this.roleList.length>2){
        let dad=this.roleList.slice(-3)
        dad.forEach((item,index)=>{
          this.newRecords[index].workOne=item.workOne
          this.newRecords[index].workTwo=item.workTwo
          this.newRecords[index].restWorker=item.restWorker
          this.newRecords[index].remake=item.remake
        })
}  // this.newRecords.push({
        //   recordId: "", // 可以根据需要设置
        //   workDate: formattedDate,
        //   workOne: morningPerson,
        //   workTwo: afternoonPerson,
        //   restWorker: restPersons.length ? restPersons[0].value : "",
        //   remake: null,
        // });

      paizneg(this.newRecords).then((response) => {
        this.$modal.msgSuccess("添加成功");
        this.xunkong = false;
        this.getList();
      });
      // 将新记录添加到 kesuwanfrom 数组中
    },
    getsList() {
      this.loading = true;
      listUssder({roleId:2}).then((response) => {
        if (this.$store.state.user.name != "admin") {
          // this.chengdan = [
          //   {
          //     value: this.$store.state.user.name,
          //     label: this.$store.state.user.name,
          //   },
          // ];
        }

        response.data.forEach((item, index) => {
          if (true) {
            this.chengdan.push({
              value: item.userName,
              label: item.userName,
            });
          }
          console.log(this.chengdan);
          this.loading = false;
        });
      });
    },
    timestampToDateString(timestamp) {
      // 创建一个新的Date对象
      var date = new Date(timestamp);

      // 使用getFullYear(), getMonth() + 1, getDate() 获取年、月、日
      // 注意：getMonth() 返回的是0-11，所以需要+1来得到正常的月份
      var year = date.getFullYear();
      var month = ("0" + (date.getMonth() + 1)).slice(-2); // 使用slice来确保月份是两位数
      var day = ("0" + date.getDate()).slice(-2); // 同上，确保日期是两位数

      // 拼接成 yyyy-MM-dd 格式
      return `${year}-${month}-${day}`;
    },
    xundan() {
      this.$refs["xundanfrom"].validate((valid) => {
        if (valid) {
          const da = this.chengdan.filter(
            (name) =>
              name.value !== this.kesuwanfrom.workOne &&
              name.value !== this.kesuwanfrom.workTwo
          );
          console.log(da);
          this.kesuwanfrom.restWorker =
            da[0].value + (da[1] ? "," + da[1].value : "");
          if (this.title !== "添加") {
            paizneg([this.kesuwanfrom]).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.xunkong = false;
              this.getList();
            });
          } else {
            paizneg([this.kesuwanfrom]).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.xunkong = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      geipaiban(this.queryParams).then((response) => {
        this.roleList = response.data;
        // this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          complaintId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined,
        });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.recordId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    // 树权限（展开/折叠）

    guanbishoukan() {
      this.kesuwanfrom = {
        recordId: "",
        workDate: this.timestampToDateString(+new Date()),
        workOne: "",
        workTwo: "",
        restWorker: "",
      };
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.kesuwanfrom.workDate = this.timestampToDateString(+new Date());
      this.xunkong = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.xunkong = true;

      this.kesuwanfrom.recordId = row.recordId;
      this.kesuwanfrom.workDate = row.workDate;
      this.kesuwanfrom.workOne = row.workOne;
      this.kesuwanfrom.workTwo = row.workTwo;
      this.kesuwanfrom.restWorker = row.restWorker;

      this.title = "修改";
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.complaintId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            updateRole(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addRole(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function () {
      if (this.form.complaintId != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.openDataScope = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.recordId || this.ids;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          console.log(roleIds);
          return deletepaiban(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/role/export",
        {
          ...this.queryParams,
        },
        `role_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
